package com.example.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.springcloud.alibaba.service.PaymentService;
import com.example.springcloud.entities.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2024-02-13
 * Time: 20:14
 */
@RestController
@Slf4j
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
    // 1. 没有 fallback 方法，会返回给前端异常界面
//    @SentinelResource(value = "fallback")
    // 2. 设置自己的 fallback 方法，fallback 只会处理该方法的异常
//    @SentinelResource(value = "fallback", fallback = "handlerFallback")
    // 3. 设置自己的 blockHandler 方法，blockHandler 只负责 sentinel 控制台配置的的违规
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler")
    // 4. 同时设置，各司其责
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler", fallback = "handlerFallback")
    // 5. 如果出现的特定的异常，要求不使用 fallback 方法处理，需要手动处理
    @SentinelResource(value = "fallback", blockHandler = "blockHandler", fallback = "handlerFallback",
            exceptionsToIgnore = IllegalArgumentException.class // 如果出现该异常，不走 fallback 方法
    )
    public CommonResult fallback(@PathVariable Long id) {
        CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);

        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
        }

        return result;
    }

    public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
        log.error("进入fallback方法...");
        return new CommonResult(444, "Global_handlerFallback....");
    }

    public CommonResult blockHandler(@PathVariable("id") Long id, BlockException e) {
        log.error("into blockHandler...");
        return new CommonResult(445, "Global_blockHandler....");
    }


    //==================  OpenFeign ========================
    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/openfeign/{id}")
    public CommonResult paymentSQL(@PathVariable("id") Long id) {
        if (id == 4) {
            throw new RuntimeException("没有该id");
        }
        return paymentService.paymentSQL(id);
    }
}

